<?php


namespace app\api\controller;
use app\common\controller\Api;
use app\common\model\User;
use app\Request;
use think\facade\Db;

class Cart extends Api
{
    protected $noNeedLogin = [];

    public function cartlist(){
        $uid = $this -> uid;
        //查询购物车商品
        $res = Db::name('cart')
            -> alias('c')
            -> join('product pr','pr.id=c.proid')
            -> where("c.uid",$uid)
            -> field("c.id as cid,c.uid,c.num,c.selected,pr.title,pr.images,pr.price,c.proid" )
            -> order("c.createtime desc") -> select();
        $count =  Db::name('cart') -> where("uid",$uid) ->  count();
        $data = ['count' => $count,'cartlist' => $res];
        $this->success('请求成功',$data);
    }
    //加入购物车
    public function addcart(){
        $request = $this->request->request();
        unset($request['token']);
        unset($request['s']);
        $request['uid'] = $this->uid;
        Db::startTrans();
        $request['createtime'] = $request['updatetime'] = time();
        $request['selected'] = 'true';
        $res = Db::name('cart') -> where(['uid'=>$this-> uid,'proid'=>$request['proid']]) -> find();
        if(empty($res)){
            $result = Db::name('cart') -> insert($request);
        }else{
            $result =   Db::name('cart') -> where(['uid'=>$this-> uid,'proid'=>$request['proid']]) -> inc('num',$request['num']) -> update();
        }
        if(!$result){
            Db::rollback();
            $this->error('操作失败');
        }else{
            Db::commit();
            $this->success('操作成功');
        }
    }
    public function cartdel(){
        $request = $this->request->request();
//        $cids = $request->delete('cids');
        $cids = $request['cids'];
//        Db::name('cart') -> whereIn('id',$cids) -> delete();
        $res = $this -> delCart($cids);
        $this->success('请求成功',$res);
    }



    public function createorder(Request $request){
        if (!$request->isPost()) $this -> error("请求方式错误");
        $obj = $request->post('obj');
        $pay_order_no = $this -> create_order_no();
        $totalPrice = floatval($obj['totalPrice']);
        $amount_price =  floatval($obj['amount_price']) ?? 0; //优惠价
        $payment_price = floatval($obj['payment_price']);
//        Db::startTrans();
        try {
            $order['user_id'] = $obj['uid'];
            $order['addressid'] = $obj['addressid'];
            $order['order_sn'] = $pay_order_no;
            $order['status'] = 1;
            $order['createtime'] = time();
            $order['goods_price'] = $totalPrice;
            $order['amount_price'] = $amount_price;//$obj['amount_price'];
            $order['payment_price'] = $payment_price;


//            $order_id = Db::name('orders')->insertGetId($order);
            $detail = [];
            $cartids ="";
            foreach ($obj['data'] as $key => $val){
                $detail[$key]['uid'] = $obj['uid'];
                $detail[$key]['orderid'] = $pay_order_no;
                $detail[$key]['proid'] = $val['gid'];
                $detail[$key]['gprice'] = $val['price'];
                $detail[$key]['quantity'] = $val['num'];
                $detail[$key]['totalprice'] = $val['price'] * $val['num'];
                $detail[$key]['createtime'] = time();
                $cartids .= $val['cartid'].',';
            }
            $dcartids = substr($cartids,0,strrpos($cartids,','));
            var_dump($dcartids);
            $user = User::where('id', $obj['uid'])->find();
            $user->money -= $amount_price;
            $user->save();
//            Db::name('orders_detail')->insertAll($detail);
//            Db::commit();
        }catch (\Exception $e){
//            Db::rollback();
            return $e->getMessage();
        }
        $openid = $obj['openId'];
        $payment = new Payment();
        $res = $payment -> pay($pay_order_no, $payment_price, '小香铺购物下单', $openid);
        if ($cartids) {
            $this->delCart($cartids);
        }
//        if ($res) {
//            return apiBack('success', '成功', '10000', $res);
//        } else {
//            return apiBack('fail', '获取订单失败', '10001');
//        }

    }






    /**
     * 删除购物车
     * @param $ids
     * @return bool
     */
    private function delCart ($ids)
    {
        $ids = explode(',', $ids);
        Db::name('cart') -> where('id', 'in', $ids)->delete();
        return true;
    }
}